using System;
using System.Globalization;
using System.Windows.Forms;

using FreeFlow.Client;

namespace FreeFlow.WinFormsControls
{
  // TODO - accept only numeric values
	/// <summary>
	/// A control to display numeric values.
	/// </summary>
	public class NumberControl : TextBox, IFillable, IRefillable
	{
    /// <summary>
    /// Creates a new <see cref="NumberControl"/> instance.
    /// </summary>
		public NumberControl()
		{
    }

    /// <summary>
    /// Triggered when a key is pressed. Swallows all keys except for digits.
    /// </summary>
    /// <param name="e">E.</param>
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
      base.OnKeyPress(e);
      string decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
      if (e.KeyChar.ToString() == decimalSeparator)
      {
        if (Text.IndexOf(decimalSeparator) > -1)
          e.Handled = true;
      }
      else if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
      {
        e.Handled = true;
      }
    }

    #region IFillable Members

    /// <summary>
    /// Renders the number control with static layout information using the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Render(FreeFlow.Client.Field field)
    {
      TextAlign = HorizontalAlignment.Right;
    }

    /// <summary>
    /// Fills the memo control with values from the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Fill(FreeFlow.Client.Field field)
    {
      if (field != null)
      {
        Text = field.Value;
        Modified = false;
      }
    }

    /// <summary>
    /// Fills the field from the control.
    /// </summary>
    /// <param name="field">Field.</param>
    public void FillField(Field field)
    {
      if (field != null)
      {
        field.Value = Text;
      }
    }

    #endregion
    #region IRefillable Members

    /// <summary>
    /// Event triggered when a refill should occur
    /// </summary>
    public event System.EventHandler Refill;

    /// <summary>
    /// Triggers a refill.
    /// </summary>
    /// <param name="e">E.</param>
    protected override void OnLeave(EventArgs e)
    {
      base.OnLeave(e);
      if (Modified)
        if (Refill != null)
          Refill(this, e);
    }

    #endregion
  }
}
